<?php
/**
 * @author Huo Wei
 * @version (2011-09-16 by Huo Wei) 创建；(2012-03-09 by Huo Wei) 注释规范化处理
 * @package Union
 */

require_rewrite(SYSTEM_PATH . 'config/union_type.php');

class union
{
    /**
     * 保存union
     * @param 过滤敏感字符后的用户提交数据 array $fields
     * 数组中各元素key顺序及说明
     * string Id  联盟Id
     * string Name 渠道名称
     * string QueryToken CPS查询页使用的标识
     * int Type 投放方式:CPS,CPC,SEM等
     * int BusinessType 业务类型：机票、酒店、活动
     * int IsValid 是否有效
     * string SourceDomain 来源域名
     * int CheckDomain 检查来源域名
     * string URL 调整的url
     * string GoogleUTM    Google Anaylitics UTM参数信息
     * string Description 说明文字，记录此联盟ID分配的具体用途
     * string Remark 备注
     * string Creator 创建者
     * string Modifier 最后一次修改者
     * string SubmitTime 申请时间
     * string GoLiveTime 上线时间
     * string LastUpdateTime 最后一次修改时间
     * @return null
     */
    private static $data_key = 'union_ids_config_key_';
    private static $union_cache_key='union_key_by_union_sign_';
    public static function insertUnion($fields)
    {
        if (!empty($fields)) {
            $db = DB_MySQLi::getInstance();
            foreach ($fields as $key => $value) {
                $field[$key] = $db->escapeString($value); //转义变量中的特殊字符
            }
            $insert_union = "insert into `union_ids` (`Id`,`Name`,`QueryToken`,`Type`,`BusinessType`,`IsValid`,`SourceDomain`,`CheckDomain`,`URL`,`GoogleUTM`,`Description`,`Remark`,`Creator`,`Modifier`,`SubmitTime`,`LastUpdateTime`,`hotelRebate`,`flightRebate`) values ('" . $fields['Id'] . "', '" . $fields['Name'] . "','" . $fields['QueryToken'] . "', '" . $fields['Type'] . "','" . $fields['BusinessType'] . "', '" . $fields['IsValid'] . "', '" . $fields['SourceDomain'] . "','" . $fields['CheckDomain'] . "', '" . $fields['URL'] . "', '" . $fields['GoogleUTM'] . "', '" . $fields['Description'] . "','" . $fields['Remark'] . "', '" . $fields['Creator'] . "', '" . $fields['Modifier'] . "', '" . $fields['SubmitTime'] . "', '" . $fields['LastUpdateTime'] . "', '" . $fields['hotelRebate'] . "', '" . $fields['flightRebate'] . "')";
            $db->query($insert_union);
        }
    }


    /**
     * 根据id获取对应union
     * @param  string $id Union id
     * @return array union信息
     */

    public static function  getUnionById($id)
    {
        if (empty($id)) {
            return array();
        }

        //从缓存中获取值
        $key = self::$data_key . $id;
        $cache = MemoryCache::getInstance();
        $data = $cache->get($key);
        //缓存没有则从配置中读取
        if (empty($data)) {
            $db = DB_MySQLi::getInstance();
            $union_sql = "select `Id`,`Name`,`QueryToken`,`Type`,`BusinessType`,`IsValid`,`SourceDomain`,`CheckDomain`,`URL`,`GoogleUTM`,`Description`,`Remark`,`Creator`,`Modifier`,`SubmitTime`,`GoLiveTime`,`LastUpdateTime`,`hotelRebate`,`flightRebate` from union_ids where Id='" . $id . "'";
            $db->query($union_sql);
            $union = $db->fetchRow_ASSOCS();
            if (!empty($union)) {
                if (empty($union['GoLiveTime'])) {
                    $union['GoLiveTime'] = "";
                } else {
                    $union['GoLiveTime'] = date("Y-m-d", strtotime($union['GoLiveTime']));
                }
                $cache->set($key, $union, 172800); //60*60*24*2
            }
            return $union;
        }
        return $data;
    }

    /**
     * 根据uid获取对应的联盟配置，如果配置中的IsValid为0时，返回空数组
     * @param string $uid 联盟ID
     * @return mixed 如果配置有效返回配置，否则返回空数组
     */
    public static function getValidUnionById($uid)
    {
        $union = self::getUnionById($uid);
        if (!empty($union) && intval($union['IsValid']) == 1) {
            return $union;
        }
        return array();
    }

    /**
     * 保存修改后的union
     * @param array $set_data 更新数据
     * @return int 更新成功返回1,否则返回0
     */
    public static function updateUnion($set_data)
    {
        if (!empty($set_data)) {
            $db = DB_MySQLi::getInstance();
            if (!empty($set_data['golivetime'])) {
                $go_live_time = "GoLiveTime='" . $set_data['golivetime'] . "',";
            }
            $update_union = "update union_ids set Id='" . $set_data['union_id'] . "',Name='" . $set_data['name'] . "',QueryToken='" . $set_data['union_sign'] . "',Type='" . $set_data['union_type'] . "',BusinessType='" . $set_data['business_type'] . "',IsValid='" . $set_data['visible'] . "', SourceDomain='" . $set_data['source_domain'] . "',CheckDomain='" . $set_data['check_domain'] . "',GoogleUTM='" . $set_data['google_utm'] . "',Description='" . $set_data['description'] . "',Remark='" . $set_data['remark'] . "',Modifier='" . $set_data['user'] . "',SubmitTime=NOW()," . $go_live_time . "LastUpdateTime=NOW(),URL='" . $set_data['url'] . "',hotelRebate='" . $set_data['hotelRebate'] . "',flightRebate='" . $set_data['flightRebate'] . "' where Id='" . $set_data['id'] . "'";
            $db->query($update_union);
            //删除对应的缓存
            self::removeCacheByUid($set_data['union_id']);
            return "1";
        } else {
            return "0";
        }
    }


    /**
     * 删除union
     * @param array union_ids
     * @return int 删除成功返回1,否则返回0
     */

    public static function delUnion($del_ids)
    {
        if (!empty($del_ids)) {
            $db = DB_MySQLi::getInstance();
            while (list($name, $value) = each($del_ids))
            {
                $del_sql = "delete from union_ids where Id='" . $value . "'";
                $db->query($del_sql);
                //删除对应的缓存
                self::removeCacheByUid($value);
            }
            return "1";
        } else {
            return "0";
        }
    }

    /**
     * 根据union标识查询符合条件的Union
     * @param stirng $token CPS查询页使用的标识
     * @return array 符合条件的union
     *
     */

    public static function findUnionByToken($token)
    {
        return self::findUnion(" where QueryToken='" . $token . "' order by SubmitTime desc");
    }

    /**
     * 查询union
     * @param string  $where 搜索条件
     * @return array 符合条件的union
     */

    public static function findUnion($where = '')
    {
        $db = DB_MySQLi::getInstance();
        $find_union_sql = "select `Id`,`Name`,`QueryToken`,`Type`,`BusinessType`,`IsValid`,`SourceDomain`,`CheckDomain`,`URL`,`GoogleUTM`,`Description`,`Remark`,`Creator`,`Modifier`,`SubmitTime`,`GoLiveTime`,`LastUpdateTime`,`hotelRebate`,`flightRebate` from union_ids " . $where;
        $db->query($find_union_sql);
        $union_array = array();
        while ($union = $db->fetchRow_ASSOCS()) {
            $union_array[] = $union;
        }
        foreach ($union_array as $key => $value) {
            if (empty($value['GoLiveTime'])) {
                $union_array[$key]['SubGoLiveTime'] = "";
            } else {
                $union_array[$key]['SubGoLiveTime'] = date("Y-m-d", strtotime($value['GoLiveTime']));
            }
            $union_array[$key]['TypeDesc'] = union_type::$type[$value['Type']];
            $union_array[$key]['BusinessTypeDesc'] = union_type::$business_type[$value['BusinessType']];
        }
        return $union_array;
    }


    /**
     * 检测unionid 是否存在
     * @param string $union_id
     * @return int 存在返回1,否则返回0
     */

    public static function checkUnionId($union_id)
    {
        if (!empty($union_id)) {
            $union = self::getUnionById($union_id);
            if (!empty($union)) {
                return "1";
            } else {
                return "0";
            }
        } else {
            return "0";
        }
    }


    /**
     * 统计符合条件的union记录数
     * @param string $table 表名称
     * @param string $where 统计条件
     * @return int 符合条件的记录数
     */

    public static function count($table, $where = '')
    {
        $db = DB_MySQLi::getInstance();
        $count_sql = "select count(Id) as num from " . $table . $where;
        $db->query($count_sql);
        $total = $db->fetchRow_ASSOCS();
        return $total['num'];
    }

    /**
     * 根据uid从Memcached中删除对应的数据
     * @param string $uid 联盟ID
     * @return bool 删除成功返回true，否则返回false
     */
    private static function removeCacheByUid($uid)
    {
        if (empty($uid)) {
            return false;
        }
        $key = self::$data_key . $uid;
        $cache = MemoryCache::getInstance();
        $cache->delete($key);
    }

    /**
     * 根据uid获取对应的域名，根域名
     * @param string $uid 联盟ID
     * @return string 对应的域名
     */
    public static function getDomainByUid($uid)
    {
        $config = self::getValidUnionById($uid);
        if (!empty($config)) {
            return trim($config['SourceDomain']);
        }
        return '';
    }

    /**
     * 根据uid配置查看该uid对应的请求是否要进行域名匹配校验
     * @param string $uid 联盟ID
     * @return bool 需要校验返回true，否则返回false
     */
    public static function isUidNeedCheckDomain($uid)
    {
        $config = self::getValidUnionById($uid);
        if (!empty($config)) {
            return intval($config['CheckDomain']) == 1 ? true : false;
        }
        return false;
    }

    /**
     * 根据uid获取对应的google analytics 的utm参数配置
     * @param string $uid 联盟ID
     * @return string 对应的utm配置串
     */
    public static function getGoogleUtmByUid($uid)
    {
        $config = self::getValidUnionById($uid);
        if (!empty($config)) {
            return trim($config['GoogleUTM']);
        }
        return '';
    }

    /**
     * 根据uid获取对应的查询标识
     * @param string $uid 联盟ID
     * @return string 对应的utm配置串
     */
    public static function getQueryTokenByUid($uid)
    {
        $config = self::getValidUnionById($uid);
        if (!empty($config)) {
            return trim($config['QueryToken']);
        }
        return '';
    }

    /**
     * 保存CPS渠道带来的标识信息，需要根据各CPS合作商提供的技术文档实现。
     * @param string $uid 联盟ID
     * @return bool 成功返回true，否则返回false。
     */
    public static function saveClientUnionInfo($uid)
    {
        if (empty($uid)) {
            return false;
        }
        //根据union_id获取对应的厂商查询标识
        $union_token = strtolower(union::getQueryTokenByUid($uid));
        if (empty($union_token)) {
            return false;
        }

        //根据联盟名字判断走哪个联盟网站的逻辑，因为厂商可能会有com,com.cn,net等域名，所以不判断后缀
        //weiyi与linktech不需要自行处理，厂商会事先访问webroot/cps/目录下的页面植入cookie
        switch ($union_token) {
            case 'eqifa':
                return Handler_union::saveInfo_yiqifa();
            case 'chahet':
                return Handler_union::saveInfo_chenet();
            case 'pubsage':
                return Handler_union::saveInfo_pubsage();
            case 'duomai':
            	return Handler_union::saveInfo_duomai();
            case 'youbibi':
            	return Handler_union::saveInfo_youbibi();
            default:
                return false;
        }
    }


    /**
     * 根据uid获取对应的合作商的独立的CPS信息，用于保存到订单数据中，之后通过查询接口
     * 返回给合作商
     * @param string $uid 联盟ID
     * @return string 对应cps信息
     */
    public static function getUnionIndetityInfo($uid)
    {
        if (empty($uid)) {
            return '';
        }
        //根据union_id获取对应的厂商查询标识
        $union_token = strtolower(union::getQueryTokenByUid($uid));
        if (empty($union_token)) {
            return '';
        }
        $union_info = '';
        //根据查询标识获取对应的信息
        switch ($union_token) {
            //领克特
            case 'lingkete':
                $union_info = Handler_union::getInfo_linktech();
                break;
            //亿玛，亿起发
            case 'eqifa':
                $union_info = Handler_union::getInfo_yiqifa();
                break;
            //唯一传媒
            case 'weiyi':
                $union_info = Handler_union::getInfo_weiyi();
                break;
            //成果
            case 'chahet':
                $union_info = Handler_union::getInfo_chenet();
                break;
            //中视网盟
            case 'ctvwm':
                $union_info = Handler_union::getInfo_zswm();
                break;
            //艾德思奇网盟
            case 'pubsage':
                $union_info = Handler_union::getInfo_pubsage();
                break;
            case 'duomai':
            	$union_info = Handler_union::getInfo_duomai();
            	break;
            case 'youbibi':
            	$union_info = Handler_union::getInfo_youbibi();
            	break;
            default:
                break;
        }

        //防止第三方传入的数据含有不安全的字符或者语句，进行base64编码
        return base64_encode($union_info);
    }


   /**
    * 生成union密钥
    * @param int $length:随机数字符串的长度
    * @return string 密钥
    */
    function random($length)
    {
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($chars) - 1;
        $string = "";
        for ($i = 0; $i < $length; $i++) {
            $string .= $chars[mt_rand(0, $max)];
        }
        return md5($string);
    }


   /**
    * 保持Union密钥
    * @param $union_sign Union唯一标识
    * @return boole 保持成功返回true,否则返回false
    */
    function saveUnionKey($union_sign)
    {
        if (empty($union_sign)) {
            return false;
        } else {
            $db = DB_MySQLi::getInstance();
            $union_key = self::random(18);
            $insert_union_key = "insert into `union_key` (`union_sign`,`union_key`,`creat_time`,`last_modi_time`) values ('" . $union_sign . "', '" . $union_key . "',NOW(),NOW())";
            $db->query($insert_union_key);
            return true;
        }
    }


    /**
     * 获取所有的union标识
     * @return array 系统中所有的union标识
     */

    function getAllUnionSign()
    {
        $db = DB_MySQLi::getInstance();
        $all_union_sign = "select distinct `QueryToken` from `union_ids`";
        $db->query($all_union_sign);
        $union_sign_array = array();
        while ($union_sign = $db->fetchRow_ASSOCS()) {
            $union_sign_array[] = $union_sign['QueryToken'];
        }
        return $union_sign_array;
    }


   /**
    * 获取已经生成密钥的union标识
    * @param $p 页码
    * @param $page_size 每页记录数
    * @return array 系统中所有已生成密钥的union标识
    */

    function getUnionSignHadKey($p = "", $page_size = "")
    {
        $db = DB_MySQLi::getInstance();
        if (empty($p) && empty($page_size)) { //无页面，每页记录数，则返回所有
            $all_union_had_key = "select `union_sign`,`union_key` from `union_key`";
        } else {
            $all_union_had_key = "select `union_sign`,`union_key`,`creat_time`,`last_modi_time` from `union_key` order by `creat_time` desc limit " . ($p - 1) * $page_size . "," . $page_size;
        }
        $db->query($all_union_had_key);
        $union_sign_array = array();
        while ($union_sign = $db->fetchRow_ASSOCS()) {
            $union_sign_array[] = $union_sign;
        }
        return $union_sign_array;
    }


   /**
    * 根据union标识获取union密钥所有信息
    * @param $union_sign Union唯一标识
    * @return array  符合条件的union密钥相关信息
    */

    function getUnionKeyByUnionSign($union_sign)
    {
        if (empty($union_sign)) {
            return array();
        } else {
            $cache_key = md5(self::$union_cache_key . $union_sign);
            $cache = MemoryCache::getInstance();
            //缓存没有则从配置中读取
            if (!$union_key = $cache->get($cache_key)) {
                $db = DB_MySQLi::getInstance();
                $union_key_sql = "select `union_sign`,`union_key`,`creat_time`,`last_modi_time` from `union_key` where `union_sign`='" . $union_sign . "'";
                $db->query($union_key_sql);
                $union_key = $db->fetchRow_ASSOCS();
                if (!empty($union_key)) {
                    $cache->set($cache_key, $union_key, 259200);//缓存三天 60*60*24*3
                } else {
                    $union_key = array();
                }
            }
            return $union_key;
        }
    }


   /**
    * 根据union标识仅获取union密钥
    * @param $union_sign Union唯一标识
    * @return array  符合条件的union密钥
    */

    function getOnlyKeyByUnionSign($union_sign)
    {
        if (empty($union_sign)) {
            return null;
        } else {
            $union_key=self::getUnionKeyByUnionSign(trim($union_sign));
            if (!empty($union_key['union_key'])) {
                return $union_key['union_key'];
            } else {
                return null;
            }
        }
    }


   /**
    *  union 密钥管理中修改union标识
    *  @param stirng $new_union_sign 新标识
    *  @param string $old_union_sign 旧标识
    *  @return boole 更新成功返回true,否则返回false
    */

    function saveModiUnionSign($new_union_sign, $old_union_sign)
    {
        if (empty($new_union_sign) || empty($old_union_sign)) {
            return false;
        } else {
            $db = DB_MySQLi::getInstance();
            $save_modi_union_sign = "update `union_key` set `union_sign` = '" . $new_union_sign . "',`last_modi_time`=NOW() where `union_sign` = '" . $old_union_sign . "'";
            $db->query($save_modi_union_sign);
            return true;
        }
    }


   /**
    * 更新Union密钥
    * @param string $union_sign Union唯一标识
    * @return boole 更新成功返回true,否则返回false
    */
    function updateUnionKey($union_sign)
    {
        if (empty($union_sign)) {
            return false;
        } else {
            $cache_key = md5(self::$union_cache_key . $union_sign);
            $cache = MemoryCache::getInstance();
            $db = DB_MySQLi::getInstance();
            $union_key = self::random(18);
            $update_union_key = "update `union_key` set `union_key` = '" . $union_key . "',`last_modi_time`=NOW() where `union_sign` = '" . $union_sign . "'";
            $db->query($update_union_key);
            $cache->delete($cache_key);
            return true;
        }

    }


   /**
     * 统计符合条件的union密钥记录数
     * @param string $where
     * @return int 记录数
     */
    public static function countUnionKey( $where = '')
    {
        $db = DB_MySQLi::getInstance();
        $count_sql = "select count(union_key) as num from `union_key`".$where;
        $db->query($count_sql);
        $total = $db->fetchRow_ASSOCS();
        return $total['num'];
    }
}

?>